package com.fang.udp;

import java.net.*;
import java.util.Scanner;

public class Server extends Thread {
    public Server() {
        super("服务器：");
    }


    @Override
    public void run() {
        try {
            DatagramSocket ds = new DatagramSocket(8896);
            byte[] b = new byte[1024];
            while(true) {
                //////////////////////////接收消息////////////////////////////////////
                DatagramPacket dp = new DatagramPacket(b,b.length);
                ds.receive(dp);
                Thread t = Thread.currentThread();

                int len = dp.getLength();
                String str = new String(b,0,len);
                System.out.println(str);


                /////////////////////////////发送消息//////////////////////////////////////////
                String s = Thread.currentThread().getName();
                Scanner sc = new Scanner(System.in);
                String strMsg = s+sc.next();
                SocketAddress sa = dp.getSocketAddress();
                DatagramPacket dp2 = new DatagramPacket(strMsg.getBytes(), strMsg.getBytes().length,
                        sa);
                ds.send(dp2);
                System.out.println(strMsg);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
